﻿namespace Beetle
{
    using System;
    using System.Collections.Generic;

    public class ObjectPool<T> : IDisposable where T: new()
    {
        protected Stack<T> mObjects;

        public ObjectPool(int counts)
        {
            this.mObjects = new Stack<T>();
            for (int i = 0; i < counts; i++)
            {
                T local = default(T);
                this.mObjects.Push((local == null) ? Activator.CreateInstance<T>() : default(T));
            }
        }

        public void Dispose()
        {
            if (typeof(T) == typeof(IDisposable))
            {
                while (this.mObjects.Count > 0)
                {
                    ((IDisposable) this.mObjects.Pop()).Dispose();
                }
            }
            this.mObjects.Clear();
        }

        public virtual T Pop()
        {
            lock (this.mObjects)
            {
                if (this.mObjects.Count > 0)
                {
                    return this.mObjects.Pop();
                }
                return ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));
            }
        }

        public virtual void Push(T obj)
        {
            lock (this.mObjects)
            {
                if (obj != null)
                {
                    this.mObjects.Push(obj);
                }
            }
        }
    }
}

